package com.zjy.financialsystemjavafx.service;

import com.zjy.financialsystemjavafx.model.entity.Account;
import com.zjy.financialsystemjavafx.util.DatabaseUtil;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 账户服务层，负责账户的增删改查及转账
 */
public class AccountService {
    private final DataSource dataSource;

    public AccountService() {
        this.dataSource = DatabaseUtil.getDataSource();
    }

    /**
     * 获取指定用户的所有账户
     */
    public List<Account> getAccounts(int userId) throws Exception {
        String sql = "SELECT account_id, account_name, account_type, current_balance, description " +
                     "FROM accounts WHERE user_id = ?";
        List<Account> list = new ArrayList<>();
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Account a = new Account();
                    a.setAccountId(rs.getInt("account_id"));
                    a.setAccountName(rs.getString("account_name"));
                    a.setAccountType(rs.getString("account_type"));
                    a.setCurrentBalance(rs.getDouble("current_balance"));
                    a.setDescription(rs.getString("description"));
                    list.add(a);
                }
            }
        }
        return list;
    }

    /**
     * 添加新账户
     */
    public boolean addAccount(int userId, String name, String type, double initBalance, String description) throws Exception {
        String sql = "INSERT INTO accounts(user_id, account_name, account_type, initial_balance, current_balance, description) " +
                     "VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setString(2, name);
            ps.setString(3, type);
            ps.setDouble(4, initBalance);
            ps.setDouble(5, initBalance);
            ps.setString(6, description);
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 更新账户信息
     */
    public boolean updateAccount(Account account) throws Exception {
        String sql = "UPDATE accounts SET account_name=?, account_type=?, current_balance=?, description=? WHERE account_id=?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, account.getAccountName());
            ps.setString(2, account.getAccountType());
            ps.setDouble(3, account.getCurrentBalance());
            ps.setString(4, account.getDescription());
            ps.setInt(5, account.getAccountId());
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 删除账户
     */
    public boolean deleteAccount(int accountId) throws Exception {
        String sql = "DELETE FROM accounts WHERE account_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, accountId);
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 转账操作
     */
    public boolean transfer(int fromId, int toId, double amount) throws Exception {
        String withdraw = "UPDATE accounts SET current_balance = current_balance - ? WHERE account_id = ?";
        String deposit  = "UPDATE accounts SET current_balance = current_balance + ? WHERE account_id = ?";
        try (Connection conn = dataSource.getConnection()) {
            conn.setAutoCommit(false);
            try (PreparedStatement ps1 = conn.prepareStatement(withdraw);
                 PreparedStatement ps2 = conn.prepareStatement(deposit)) {
                ps1.setDouble(1, amount);
                ps1.setInt(2, fromId);
                ps1.executeUpdate();

                ps2.setDouble(1, amount);
                ps2.setInt(2, toId);
                ps2.executeUpdate();

                conn.commit();
                return true;
            } catch (Exception e) {
                conn.rollback();
                throw e;
            }
        }
    }
} 